import { login, logout, getUsersInfo, findMenuList } from '@/api/user'
import { getToken, setToken, removeToken, setCookie } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { getPic } from '@/api/uploadPic'

/* Layout */
import Layout from '@/layout'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  resetroute: [],
  menulist: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_MENU: (state, menulist) => {
    state.menulist = menulist
  },
  RESET_ROUTE: (state, resetroute) => {
    state.resetroute = resetroute
  },
  GET_USER_ID: (state, userId) => {
    state.userId = userId
  },
}

/* 处理router数据为实际数据*/
function filiteRoute(route) {
  const router = []
  for (let j = 0; j < route.length; j++) {
    router[j] = {}
    //  一级菜单
    router[j].path = '/' + route[j].url
    router[j].component = Layout
    router[j].meta = { title: route[j].name, icon: 'tree-table' }

    if(route[j].children && route[j].children.length > 0){
      if(route[j].url === 'product'){
        const routeAppend = childFun(route[j].children,route[j].url)
        routeAppend.push({
          path: '/product/product/edit',
          component: () => import('@/views/product/product/edit'),
          meta: { title: '编辑产品', icon: 'table', noCache: true },
          hidden: true
        })
        router[j].children = routeAppend
      }else{
        router[j].children = childFun(route[j].children,route[j].url)
      }
    }else{
      router[j].children = []
    }
  }
  router.push({ path: '*', redirect: '/404', hidden: true })
  return router
}

function childFun(child,fileUrl){
  const childRouter = []
  for( let i =0; i<child.length; i++ ){
    childRouter[i] = {}
    if(child[i].children && child[i].children.length > 0){
      childRouter[i].path = '/' + child[i].url
      childRouter[i].children = childFun(child[i].children,child[i].url)
      childRouter[i].component = ()=>  import(`@/views/${child[i].url}/${child[i].url}`)
    }else{
      childRouter[i].children = []
      childRouter[i].path = child[i].url + '/list'
      childRouter[i].component = ()=> import(`@/views/${fileUrl}/${child[i].url}/list`)
      childRouter[i].name = fileUrl + '-' + child[i].url
    }
    childRouter[i].meta = { title: child[i].name, icon: 'table' }
  }
  return childRouter
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, imageCode } = userInfo
    return new Promise((resolve, reject) => {
      login({ phone: username.trim(), password: password, securityCode: imageCode, appId: '2c91363b6c2744e5016c279271490000' }).then(response => {
        // commit('SET_TOKEN', 'admin-token')
        // setToken('editor-token')
        commit('SET_TOKEN', response.object)
        setToken(response.object)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getUsersInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUsersInfo(state.token).then(response => {
        const roles = ['admin']
        commit('SET_ROLES', roles)
        //用户id
        setCookie('pid', response.object.id)
        commit('SET_NAME', response.object.name)
        // profilePhoto
        if(response.object.profilePhoto){  // 用户设置了头像
          // getPic(response.object.profilePhoto).then((response) => {
            commit('SET_AVATAR', response.object.profilePhoto)
            // commit('SET_AVATAR', response.object)
          // }).catch(error => {
          //   reject(error)
          // })
        }else{  //  用户未设置头像（默认头像）
          commit('SET_AVATAR', 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
        }
        commit('SET_INTRODUCTION', 'I am a super administrator')
        const data = {}
        data.roles = roles
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  //获取菜单
  findMenuList({ commit, state }) {
    return new Promise((resolve, reject) => {
      findMenuList(state.token,'2c91363b6c2744e5016c279271490000','2c91363b6c2744e5016c2794cd360001').then((response) => {
        const data = response.object
        if(data){
          const router = filiteRoute(response.object)
          commit('SET_MENU', router)
          commit('RESET_ROUTE', router)
        }else{
          const router = []
          commit('SET_MENU', router)
          commit('RESET_ROUTE', router)
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout({token: state.token}).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // Dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)
      const { roles } = await dispatch('findMenuList')
      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
